<template>
    <div class="xdh-tree">
         <el-tree :data="regionTree" node-key="qhdm" :props="{label:'qhmc', children: 'children'}"
         default-expand-all>
           <div class="custom-tree-node" slot-scope="{node,data}">
              <div :class="{node: true,active: data.qhdm === currentNodeId}" @click="selectNode(node,data)">
                {{data.qhmc}}{{node.isLeaf ? `(${data.sl || 0})`: ''}}
                </div>
           </div>
    </el-tree>
    </div>
</template>
<script>
import {mapState} from 'vuex'
import {GET_REGIONS, GET_SEARCH_RESULT_COUNTS} from '@/base/types'
import {listToTree} from '@/utils/convert'
export default {
    computed: {
        ...mapState(['sRegion', 'mySearchResult_query']),
        regionTree() {
          if(!this.sRegion.regions) {
            return [];
          }
        let regions = JSON.parse(JSON.stringify(this.sRegion.regions.list));
        if(this.sRegion.searchResultCounts) {
           regions.forEach(item => {
             let countObj = this.sRegion.searchResultCounts.list.find(r => r.dqdm === item.qhdm);
             if(countObj) {
               item.sl = countObj.sl;
             }
           })
        }
        let tree = listToTree(regions, '0', 0, {
            id: 'qhdm', 
            parentId: 'sjdm', 
            children: 'children',
            level: 'level',
            order: 'order'
          })
        return tree
      }
    },
    data () {
      return {
        currentNodeId: ''
      }
    },
    methods: {
      selectNode(node, data) {
        if(node.isLeaf) {
          this.currentNodeId = data.qhdm;
          let query = Object.assign({}, this.mySearchResult_query, {region: this.currentNodeId})
          this.$store.commit('mySearchResult_query', query)
        }
      }
    },
    created() {
       this.$store.dispatch(GET_REGIONS);
       let queryCount = Object.assign({}, this.mySearchResult_query, {region: undefined})
       console.log(queryCount)
        this.$store.dispatch(GET_SEARCH_RESULT_COUNTS, queryCount).then(r => {
          console.log(r)
        })
        this.currentNodeId = this.mySearchResult_query.region;
        console.log(this.currentNodeId)
        if(this.currentNodeId) {
          let query = Object.assign({}, this.mySearchResult_query, {region: this.currentNodeId})
          this.$store.commit('mySearchResult_query', query)
        }
    }
  }
</script>